package cn.matrix42.potoo.jdbc.dialect;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

public class DialectFactoryLoader {

    public static DialectFactory load(String url) {
        ServiceLoader<DialectFactory> serviceLoader = ServiceLoader.load(DialectFactory.class);
        Iterator<DialectFactory> iterator = serviceLoader.iterator();
        List<DialectFactory> matchedFactories = new ArrayList<>();
        while (iterator.hasNext()) {
            DialectFactory factory = iterator.next();
            if (factory.acceptsURL(url)) {
                matchedFactories.add(factory);
            }
        }
        if (matchedFactories.size() > 1) {
            throw new IllegalStateException("found multiple matched factory. Please check.");
        }
        if (matchedFactories.size() == 0) {
            throw new IllegalStateException("no matched factory found.");
        }
        return matchedFactories.get(0);
    }

}
